<?php

/**
 * 公共函数
 * 
 * @author bing.peng
 */

/**
 * 加载类库，并实例化，如果已经实例化，则直接返回类对象
 * @param $class
 * @return obj
 */
function load_class($class) {
	static $objects = array();

	$class_name = ucwords($class);
	if ( isset($objects[$class]) ) {
		return $objects[$class];
	}
	
	// 类文件不存在 
	
	if ( $class == 'db' ) {
		require( TATUPATH . 'libs/DB.php' );
		$config = get_config();	
		$objects['db'] = new DB(
			$config['db_username'], 
			$config['db_password'], 
			$config['db_name'], 
			$config['db_hostname']
		);
		return $objects['db'];
	}
	else if( $class == 'tatu' ) {
		$balm = load_class('tigerbalm');
		require( ABSPATH . $balm ->fetch_src() );

		$class = $balm->fetch_class();
		//$method = $TB->fetch_func();
		$objects['tatu'] = new $class();
		return $objects['tatu'];
	}
	// 普通类库
	else {	
		if( ! file_exists( TATUPATH . 'libs/' . $class_name . '.php' ) ) {
			exit("The '$class_name' lib does not exist.");
		}
		
		require( TATUPATH . 'libs/'. $class_name .'.php' );
		$objects[$class] = new $class_name();
		return $objects[$class];
	}
}

/**
 * 获取配置信息
 * @return array();
 */
function get_config() {
	static $main_conf;
	
	if( ! isset($main_conf) ) {
		if( ! file_exists( ABSPATH . 'configs.php' ) ) {
			exit('The configuration file config.php does not exist.');
		}
		
		require( ABSPATH . 'configs.php' );

		if ( ! isset($config) OR ! is_array($config)) {
			exit('Your config file does not appear to be formatted correctly.');
		}
		$main_conf = $config;
	}
	return $main_conf;
}

function get_domain() {
	$domain = $_SERVER ['HTTP_HOST'];
	if(preg_match('/www.*/', $domain)) {
		$domain = str_replace( 'www.', '', $domain );	
	}
	return $domain;
}

/**
 * 获取基础URL
 * @return string
 */
function base_url() {
	$config = get_config();
	return $config['base_url'];
	//return 'http://'.$_SERVER ['HTTP_HOST'] . '/';
}

/**
 * 构造网站URL
 * @param $uri
 * @return string
 */
function site_url($uri) {
	$config = get_config();
	return base_url() . $config['index_page'] . '/' . $uri;
}

/**
 * 请求重定向
 * @param $uri
 * @return unknown_type
 */
function redirect($uri) {
	header("Location:" . site_url($uri));
}

/**
 * 显示错误信息
 * @param $message
 * @return void
 */
function show_error( $message ) {
	$ex = load_class('exceptions');
	$ex->show_error('An Error Was Encountered', $message);
	exit;
}

/**
 * PHP错误处理句柄
 * @param $severity
 * @param $message
 * @param $filepath
 * @param $line
 * @return void
 */
function _exception_handler($severity, $message, $filepath, $line) {
	//if ($severity == E_STRICT || $severity == E_NOTICE) {
	if ($severity == E_STRICT) {
		return;
	}
	$ex = load_class('exceptions');
	$ex->show_php_error($severity, $message, $filepath, $line);
	exit;
}

/**
 * 参数获取方法GET
 * @param $name
 * @return string
 */
function get( $name ) {
	return isset($_GET[$name]) ? $_GET[$name] : false;
}

?>